<template>
  <div>
    <van-button :disabled="disabled"
                @click="sendCode"
                size="small"
                class="code">{{count === 0 ? codeText : count + 's'}}</van-button>
  </div>
</template>

<script>
import { sendMobileCode } from '@/api/login'
export default {
  name: '',
  props: {
    mobile: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      disabled: false,
      codeText: '获取验证码',
      timer: null,
      count: 0
    }
  },
  created () {

  },
  methods: {
    // 发送验证码
    async sendCode () {
      if (!this.mobile) {
        this.$toast.fail('请输入手机号')
        return
      }
      const _p = { mobile: this.mobile, event: 'changemobile' }
      const { code, msg } = await sendMobileCode(_p)
      if (code !== 1) return this.$toast.fail(msg)
      this.startTimer()
    },
    // 启动倒计时
    startTimer () {
      this.disabled = true
      this.count = 60
      this.codeText = '重新发送'
      this.timer = setInterval(() => {
        this.count--
        console.log(this.count)
        if (this.count === 0) {
          clearInterval(this.timer)
          this.disabled = false
        }
      }, 1000)
    }
  }
}
</script>

<style scoped lang="less">
.code {
  width: 83px;
  height: 30px;
  background: linear-gradient(180deg, #68e0cf 0%, #209cff 100%);
  opacity: 1;
  border-radius: 4px;
  color: #ffffff;
  font-size: 10px;
}
</style>
